package cc.shacocloud.mirage.kotlin.restful

import cc.shacocloud.mirage.kotlin.mirageLaunch
import cc.shacocloud.mirage.restful.Filter
import cc.shacocloud.mirage.restful.RoutingContext
import io.vertx.core.Promise

/**
 * 基于 kotlin 的协程过滤器处理器
 *
 * @author 思追(shaco)
 *
 */
interface CoroutineFilter : Filter {

    /**
     * 转为协程处理方法
     */
    override fun doFilter(context: RoutingContext, doFilterFuture: Promise<RoutingContext>) {
        mirageLaunch {
            try {
                val result = doFilter(context)
                doFilterFuture.complete(result)
            } catch (t: Throwable) {
                doFilterFuture.fail(t)
            }
        }
    }

    /**
     * 转为协程处理方法
     */
    override fun destroy(destroyFuture: Promise<Void>) {
        mirageLaunch {
            try {
                destroy()
                destroyFuture.complete();
            } catch (t: Throwable) {
                destroyFuture.fail(t)
            }
        }
    }

    /**
     * @see #doFilter
     */
    suspend fun doFilter(context: RoutingContext): RoutingContext {
        return context
    }

    /**
     * @see #destroy
     */
    suspend fun destroy() {}

}